<template>
  <div class="course_detail">
    <div
      ref="videoPlayer"
      v-video-player:myVideoPlayer="playerOptions"
      class="confVideo vjs-custom-skin video-player"
      :playsinline="true"
      customEventName="customstatechangedeventname"
      @ready="playerReadied"
      @loadeddata="onPlayerLoadeddata($event)"
      @canplay="onPlayerCanplay($event)"
      @canplaythrough="onPlayerCanplaythrough($event)"
      @play="onPlayerPlay($event)"
      @playing="onPlayerPlaying($event)"
      @timeupdate="onPlayerTimeupdate($event)"
      @pause="onPlayerPause($event)"
      @waiting="onPlayerWaiting($event)"
      @ended="onPlayerEnded($event)"
      @statechanged="playerStateChanged($event)"
    />
    <div class=" detail_info detail_box clearfix">
      <div class="layout_left">
        <ul class="course_tab clearfix">
          <li :class="{on: tab == 'info'}"><a href="javascript:" @click="tab = 'info'">课程介绍</a></li>
          <li :class="{on: tab == 'big'}"><a href="javascript:" @click="tab = 'big'">课程目录</a></li>
        </ul>
        <div v-if="tab == 'info'" class="content_info">
          <div class="introduce" v-html="courseInfo.introduce" />
        </div>
        <div v-if="tab == 'big'" class="content_info">
          <y-catalog :list="courseInfo.chapterRespList" :play-period="playPeriod" @playfunc="videoPlay" />
        </div>
      </div>
      <div class="layout_right">
        <div class="teacher_info clearfix">
          <span class="head">讲师简介</span>
          <div class="teacher_msg" />
        </div>
      </div>
    </div>
    <!-- <bottom /> -->
  </div>
</template>
<script>
import YCatalog from '@/components/course/Catalog'
import cookies from '@/utils/cookies'
import { courseDetail, studyProgress, userCourseDetail } from '~/api/course.js'
// import Bottom from '@/components/common/Bottom'

export default {
  components: {
    // Bottom,
    YCatalog
  },
  async asyncData(context) {
    try {
      const result = {}
      const token = cookies.getInServerToken(context.req)
      console.log('token', token)
      if (token) {
        // 登录
        const courseData = await userCourseDetail({ courseId: context.params.id }, token)
        result.courseInfo = courseData
        if (courseData.lecturerResp) {
          result.teacherInfo = courseData.lecturerResp
        }
      } else {
        // 没登录
        const courseData = await courseDetail({ courseId: context.params.id })
        result.courseInfo = courseData
        if (courseData.lecturerResp) {
          result.teacherInfo = courseData.lecturerResp
        }
      }
      return result
    } catch (e) {
      console.error(e)
      context.error({ message: 'Data not found', statusCode: 404 })
    }
  },
  data() {
    return {
      tab: 'info',
      playPeriod: '', // 当前播放课时
      userStudy: {}, // 进度
      playerOptions: {
        techOrder: ['html5', 'flash'], // 兼容顺序,使用flash播放，可以播放flv格式的文件
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放
        notSupportedMessage: '此视频暂无法播放!', // 无法播放时显示的信息
        sourceOrder: true,
        loop: false, // 导致视频一结束就重新开始。
        // preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        muted: true, // 默认情况下将会消除任何音频。
        language: 'zh-CN',
        // aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: false, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        hls: true, // 启用hls？
        flash: {
          hls: { withCredentials: false }
          // swf: '/videojs/video-js.swf'//放在static或着public下面文件夹中的videojs文件夹中 当引入js文件中统一定义时此处可省略
        },
        html5: { hls: { withCredentials: false }},
        sources: [
          {
            type: 'video/mp4', // 资源格式写法：'video/mp4'
            src: 'http://localhost:9000/education/预览视频1.mp4' // 本地资源地址，注意：本地资源存放在public文件夹中，本文视频资源路径public/video/1.mp4
          }
        ],
        poster: 'https://static.roncoos.com/os/001.jpg', // 你的封面地址
        // width: document.documentElement.clientWidth,
        height: this.fileAreaHeight, // 设置高度，fluid需要设置成flase
        // 配置控制栏
        controlBar: {
          volumePanel: {
            inline: false // 音量调节是否水平
          },
          timeDivider: true, // 时间分割线
          currentTimeDisplay: true, // 当前播放位置
          durationDisplay: true, // 总时间
          progressControl: true, // 进度条
          remainingTimeDisplay: false, // 剩余时间
          fullscreenToggle: true // 全屏按钮
        }
      }
    }
  },
  head() {
    return {
      title: this.courseInfo.courseName + '-' + this.$store.state.websiteInfo.websiteName
    }
  },
  mounted() {
    console.log('this is current videojs instance object', this.myVideoPlayer)
    if (this.courseInfo.allowStudy) {
      this.tab = 'big'
    }

    if (this.courseInfo.allowStudy) {
      // 可以播放，自动获取最后学习的课程
      /*
      playSign({ courseId: this.courseInfo.id, clientIp: '172.0.0.1' }).then(res => {
        this.playPeriod = res.periodId
        this.play(res, false)
      })
      */
    }

    window.s2j_onVideoPause = (vid) => {
      // 暂停
      clearInterval(this.progressInterval)
    }

    window.s2j_onVideoPlay = (vid) => {
      // 播放
      this.progressInterval = setInterval(() => {
        this.studyRecord()
      }, 3000)
    }

    window.s2j_onPlayOver = (vid) => {
      // 播放完成
      clearInterval(this.progressInterval)
      this.studyRecord()
    }
  },
  methods: {
    videoPlay(periodId) {
      if (this.courseInfo.allowStudy) {
        window.scrollTo(0, 0)
        /*
        playSign({ periodId: periodId, clientIp: '172.0.0.1' }).then(res => {
          this.playPeriod = res.periodId
          this.play(res, true)
        })
        */
      } else {
        this.$msgBox({
          content: '购买后才可以学习',
          isShowCancelBtn: false
        })
        return false
      }
    },
    play(data, autoplay) {
      const box = this.$refs.watchVideo.$refs.videobox
      if (this.player) {
        this.player.changeVid({
          'forceH5': true,
          'code': data.code,
          'playsafe': data.token,
          'ts': data.ts,
          'sign': data.sign,
          'vid': data.vid,
          'watchStartTime': data.startTime,
          autoplay: autoplay
        })
      } else {
        this.player = window.polyvObject('#player').videoPlayer({
          'width': box.offsetWidth,
          'height': box.offsetHeight,
          'forceH5': true,
          'code': data.code,
          'playsafe': data.token,
          'ts': data.ts,
          'sign': data.sign,
          'vid': data.vid,
          'watchStartTime': data.startTime,
          autoplay: autoplay
        })
      }

      this.userStudy.studyId = data.studyId
      this.userStudy.resourceId = data.resourceId
    },
    // 记录进度
    studyRecord() {
      this.userStudy.totalDuration = this.getDuration()
      this.userStudy.currentDuration = this.getCurrentTime()
      studyProgress(this.userStudy).then(res => {
        if (res === 'OK') {
          // 完成，暂停同步
          clearInterval(this.progressInterval)
        }
      })
    },
    // 获取视频当前播放时长
    getCurrentTime() {
      if (this.player && this.player.j2s_getCurrentTime) {
        return this.player.j2s_getCurrentTime()
      }
      return 0
    },
    // 获取视频总时长
    getDuration() {
      if (this.player && this.player.j2s_getDuration) {
        return this.player.j2s_getDuration()
      }
      return 0
    },
    // --------------------视频播放-开始-------------------- */
    // 初始化话播放-在onPlayerCanplay中调用
    initPlay(player) {
      console.log('initPlay>当前视频播放器实例对象', this.player)
      player.play()
    },

    /* 视频播放 */
    // 视频准备完毕
    playerReadied(player) {
      console.log('Readied>视频准备完毕!', player)
    },

    // 视频加载完成
    onPlayerLoadeddata(player) {
      console.log('Loadeddata>视频加载完成!', player)
    },

    // 可以播放视频
    onPlayerCanplay(player) {
      console.log('Canplay>可以播放视频!', player)
      // this.initPlay(player);
    },

    // 拖动视频条会触发事件-视频暂停>可以播放视频>可以播放视频至拖动位置>视频播放>视频加载中>可以播放视频>视频播放中>视频加载中>可以播放视频>视频播放中>视频加载中>可以播放视频>视频播放中>可以播放视频至拖动位置
    // 可以播放视频至拖动位置
    onPlayerCanplaythrough(player) {
      console.log('Canplaythrough>可以播放视频至拖动位置!', player)
    },

    // 视频播放
    onPlayerPlay(player) {
      console.log('Play>视频播放!', player)
    },

    // 视频播放中
    onPlayerPlaying(player) {
      console.log('Playing>视频播放中!', player)
    },

    // 视频时间更新中
    onPlayerTimeupdate(player) {
      // console.log('Timeupdate>视频时间更新中!', player);
    },

    // 视频暂停
    onPlayerPause(player) {
      console.log('Pause>视频暂停!', player)
    },

    // 视频加载中
    onPlayerWaiting(player) {
      console.log('Waiting>视频加载中!', player)
    },

    // 视频状态改变
    playerStateChanged(playerCurrentState) {
      console.log('StateChanged>视频状态改变', playerCurrentState)
    },

    // 视频播放结束
    onPlayerEnded(player) {
      console.log('Ended>视频播放结束!', player)
    },
    // 切换视频
    playVideo(url) {
      if (url) {
        this.playerOptions.sources = [
          {
            type: 'video/mp4',
            autoplay: true,
            src: 'http://172.19.82.59:1234/test' // 本地资源地址，注意：本地资源存放在 static 文件夹中，本文视频资源路径 static/topicMaterial/1.mp4
          }
        ]
      } else {
        this.playerOptions.sources = []
      }
    }
    // --------------------视频播放-结束-------------------- */
  }
}
</script>
<style lang="scss" rel="stylesheet/scss">
.course_detail {
  .detail_info {
    margin: 20px auto 60px;
    width: 1200px;
  }

  .layout_left {
    width: 920px;
    float: left;

    .info_body {
      margin-bottom: 30px;
    }
  }

  .course_tab {
    padding-left: 30px;
    background: #fff;
    border-radius: 8px;
    margin-bottom: 20px;

    li {
      float: left;
      height: 66px;
      line-height: 66px;
      margin-right: 80px;

      &.on {
        border-bottom: 2px solid #D51423;

        a {
          color: #D51423;
        }
      }

      a {
        color: #000;
        font-size: 14px;
        font-weight: 700;

        &:hover {
          text-decoration: none;
          color: #D51423;
        }
      }
    }
  }

  .content_info {
    padding: 30px;
    background: #fff;
    border-radius: 8px;
    min-height: 400px;

    .title {
      border-left: 3px solid #000;
      padding-left: 12px;
      font-size: 16px;
      color: #000;
      font-weight: 700;
      margin-bottom: 25px;
    }

    .introduce {
      font-size: 14px;
      line-height: 30px;
      color: #333;
      padding-left: 8px;
    }
  }

  .layout_right {
    width: 260px;
    float: right;
  }

  .teacher_info {
    background: #fff;
    border-radius: 8px;
    position: relative;
    min-height: 180px;

    .head {
      display: block;
      line-height: 60px;
      height: 60px;
      padding-left: 20px;
      font-size: 14px;
      color: #333;
      border-bottom: 1px solid rgb(228, 228, 228);
    }

    .teacher_phone {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: rgb(228, 228, 228);
      text-align: center;
      line-height: 46px;
      font-size: 13px;
      color: #999;
      float: left;
      margin: 0px 10px 0 10px;

      img {
        width: 46px;
        height: 46px;
        border-radius: 50%;
      }
    }

    .teacher_msg_right {
      width: 235px;
      float: right;
      margin: 12px 15px 12px 12px;
      line-height: 20px;
    }

    .teacher_name {
      font-size: 18px;
      font-weight: 700;
      color: #333;
      margin: 5px 0;
    }

    .teacher_position {
      font-size: 12px;
      color: #333;
      margin-bottom: 5px;
    }
  }
}
</style>
